//
//  TKPersonalInfoViewController.m
//  Ticket
//
//  Created by 小禹宝宝 on 2017/10/18.
//  Copyright © 2017年 cy55. All rights reserved.
//

#import "TKPersonalInfoViewController.h"
#import "TKEditPersonalInfoViewController.h"
#import "TKPersonalInfoTableViewCell.h"
#import "TKPersonalInfoHeaderView.h"
#import <ActionSheetPicker-3.0/ActionSheetPicker.h>
#import "IJImagesPicker.h"

@interface TKPersonalInfoViewController ()
<UITableViewDelegate,
UITableViewDataSource,
UIGestureRecognizerDelegate>
@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic, strong) TKPersonalInfoHeaderView *topView;
@property (nonatomic, strong) IJImagesPicker *imagesPicker;

@property (nonatomic, copy) NSString *personalNickname;
@property (nonatomic, copy) NSString *personalPhoneNumber;
//@property (nonatomic, copy) NSString *personalCity;
//@property (nonatomic, assign) NSInteger selecteCityIndex;
@property (nonatomic, copy) NSString *personalSexString;
@property (nonatomic, assign) NSInteger personalGender;
@property (nonatomic, copy) NSString *personalIntro;
@property (nonatomic, copy) NSString *personalPortrait;
@property (nonatomic, strong) NSArray *RegionArray;
@property (nonatomic, strong) NSArray *sexArray;
@end

@implementation TKPersonalInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"个人信息";
    [self ks_setupLeftBackBarButtonItemWithColor:nil];
    [self ks_setupRightButtonItemWithTitle:@"提交" image:nil highLightedImage:nil];
    [self configInfo];
    [self creatTableview];
    [self creaTableHeaderView];
}

- (void)creatTableview{
    
    _tableView = ({
        UITableView * tableView = [UITableView new];
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //        tableView.backgroundColor = [UIColor redColor];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        
        [tableView registerNib:[UINib nibWithNibName:@"TKPersonalInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"TKPersonalInfoTableViewCell"];
//        [tableView registerNib:[UINib nibWithNibName:@"BLPersonalInfoSecondCell" bundle:nil] forCellReuseIdentifier:@"BLPersonalInfoSecondCell"];
        tableView.translatesAutoresizingMaskIntoConstraints = NO;
//        tableView.scrollEnabled =NO; 
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.view).offset(0);
            //            make.size.with.equalTo(self.view);
            make.size.height.equalTo(@(354));
        }];
        
        tableView;
    });
}


- (void)creaTableHeaderView {
    self.topView = [[[NSBundle mainBundle] loadNibNamed:@"TKPersonalInfoHeaderView" owner:nil options:nil] firstObject];
    self.tableView.tableHeaderView = self.topView;
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.tableView);
        make.height.mas_equalTo(75);
    }];
    self.topView.iconImageView.layer.cornerRadius = self.topView.iconImageView.bounds.size.width/2;
    self.topView.iconImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.topView.iconImageView.layer.masksToBounds = YES;
    [self.topView.iconImageView sd_setImageWithURL:[NSURL URLWithString:self.personalPortrait] placeholderImage:[UIImage imageNamed:@"icon_placeholder"]];
    UITapGestureRecognizer * headerTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapheaderView:)];
    headerTap.numberOfTouchesRequired = 1; //手指数
    headerTap.numberOfTapsRequired = 1; //tap次数
    headerTap.delegate= self;
    [self.topView addGestureRecognizer:headerTap];
}

- (void)configInfo {
    if (self.personalInfo) {
        self.personalNickname = self.personalInfo.name;
        
        self.personalIntro = self.personalInfo.intro;
        self.personalPhoneNumber = self.personalInfo.mobile;
        self.personalSexString = [self.personalInfo genderString];
        self.personalGender = self.personalInfo.gender;
//        self.personalCity = self.personalInfo.city;
        self.personalPortrait = self.personalInfo.portrait;
    }
    //地区暂时写死
//    self.personalCity = @"北京市";
//    [self prepareRegionPickerData];
    [self prepareSexPickerData];
}

- (void)prepareSexPickerData {
    NSMutableArray *sexArray = @[@"女", @"男", @"未知"].mutableCopy;
    self.sexArray = [sexArray copy];
}
/*
- (void)prepareRegionPickerData {
    NSArray *regions = [BLApiSystem loadLocalRegion];
    NSMutableArray *marray = [NSMutableArray array];
    [regions enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BLTagItem *item = [BLTagItem new];
        item.name = obj[@"name"];
        item.value = obj[@"id"];
        
        [marray addObject:item];
    }];
    self.RegionArray = [marray copy];
}
*/
#pragma tableView--delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 51;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TKPersonalInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TKPersonalInfoTableViewCell" forIndexPath:indexPath];
    switch (indexPath.row) {
        case 0:
        {
            cell.titleLabel.text = @"姓名";
            if (self.personalNickname.length > 0) {
                cell.contentLabel.text = self.personalNickname;
            }
        }
            break;
        case 1:
        {
            cell.titleLabel.text = @"性别";
            if (self.personalSexString.length > 0) {
                cell.contentLabel.text = self.personalSexString;
            }
        }
            break;
        case 2:
        {
            cell.titleLabel.text = @"手机";
            if (self.personalPhoneNumber.length > 0) {
                cell.contentLabel.text = self.personalPhoneNumber;
            }
        }
            break;
        case 3:
        {
            cell.titleLabel.text = @"个人签名";
            if (self.personalIntro.length > 0) {
                cell.contentLabel.text = self.personalIntro;
            }
        }
            break;


        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        {
//            cell.titleLabel.text = @"姓名";
            TKEditPersonalInfoViewController *edVC = [[TKEditPersonalInfoViewController alloc] init];
            @weakify(self)
            edVC.contentBlock = ^(NSString *name) {
                @strongify(self)
                self.personalNickname = name;
                [self.tableView reloadData];
            };
            [KSNavi push:edVC];

        }
            break;
        case 1:
        {
            //性别
            if (!self.personalInfo) {
                self.personalGender = 2;
            }
            @weakify(self)
            ActionSheetStringPicker *picker = [[ActionSheetStringPicker alloc] initWithTitle:@"性别" rows:self.sexArray initialSelection:self.personalGender doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                @strongify(self)
                self.personalSexString = selectedValue;
                self.personalGender = selectedIndex;
                [self.tableView reloadData];
            } cancelBlock:^(ActionSheetStringPicker *picker) {
                
            } origin:self.view];
            
            UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:nil action:nil];
            [picker setCancelButton:cancelButton];
            UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:nil action:nil];
            [picker setDoneButton:doneButton];
            picker.tapDismissAction = TapActionCancel;
            [picker showActionSheetPicker];

        }
            break;
        case 2:
        {
//            cell.titleLabel.text = @"地区";
        }
            break;
        case 3:
        {
            TKEditPersonalInfoViewController *edVC = [[TKEditPersonalInfoViewController alloc] init];
            @weakify(self)
            edVC.contentBlock = ^(NSString *intro) {
                @strongify(self)
                self.personalIntro = intro;
                [self.tableView reloadData];
            };
            [KSNavi push:edVC];
        }
            break;
            
        default:
            break;
    }

}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [BLColorConfig backgroundColor];
    UIButton *quitBtn = [[UIButton alloc] init];
    CGFloat btnW = 335;
    CGFloat btnH = 40;
    quitBtn.frame = CGRectMake((mScreenWidth-btnW)/2, (75-btnH)/2, btnW, btnH);
    [quitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [quitBtn setBackgroundColor:[BLColorConfig mainColor]];
    [quitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [quitBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:quitBtn];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 75;
}


#pragma mark -Aciton
- (void)tapheaderView: (UITapGestureRecognizer *)gesture
{   //1.调取相册获取图片
    [self.imagesPicker pickImageWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary allowsEditing:YES completion:^(NSDictionary<NSString *,id> * _Nullable info) {
        NSLog(@"%@",info);
        UIImage *selectedImg = [[UIImage alloc] init];
        if (info) {
            NSDictionary *mediaInfo = info;
            NSData *imgData;
            selectedImg = [mediaInfo objectForKey:UIImagePickerControllerEditedImage];
            if (UIImagePNGRepresentation(selectedImg) == nil) {
                imgData = UIImageJPEGRepresentation(selectedImg, 0.7);
                //压缩图片，方便上传
            } else {
                imgData = UIImagePNGRepresentation(selectedImg);
            }
            [self uploadheaderImage:imgData];
        }
    }];
}

- (void)uploadheaderImage:(NSData *)imageData {
    [self ks_showProgress];
        NSString *device = @"1";
        NSString *curtime = [PublicTool getNowTimeStamp];
        NSString *os_version = [SystemHelper osVersion];
        NSString *version = [SystemHelper appVersion];
        //拼接sign
        NSString *user_id = [TKAccountManager sharedManager].accountInfo.result.info.user_id;
        NSString *sign = [BLApi configSign:user_id andCurtime:curtime];
    NSDictionary *params = @{@"device":device,@"curtime":curtime,@"os_version":os_version,@"version":version,@"user_id":user_id,@"sign":sign,@"type":@"1"};
    @weakify(self);
    [BLApi PostImageToUrl:URL_Image_uploading image:imageData Params:params didFinish:^(id json, NSError *error) {
        @strongify(self);
        [self ks_hideProgress];
        if (error) {
            [self ks_showToast:error.domain];
        } else {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
            NSDictionary *dcit = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
            NSString *succeed = dcit[@"errmsg"];
            if ([succeed isEqualToString:@"ok"]) {
                NSDictionary *result = dcit[@"result"];
                NSDictionary *info = result[@"info"];
                NSString *url = info[@"url"];
                self.topView.iconImageView.image = [UIImage imageWithData:imageData];
                [self ks_showToast:@"头像上传成功"];
                //拿到url并存储
                [TKAccountManager sharedManager].accountInfo.result.info.portrait = url;
                [TKAccountManager saveAccountInfo];
            } else {
                [self ks_showToast:@"头像上传失败，请重试~"];

            }
        }

    }];
}

-(void)ks_rightButtonPressed:(id)sender {
    //提交数据
    NSLog(@"提交数据");

    if (self.personalNickname.length == 0 || self.personalIntro.length == 0 ) {
        [self ks_showToast:@"请将资料填写完整再保存"];
        return;
    }
    NSString *genderStr = [NSString stringWithFormat:@"%ld",(long)self.personalGender];
    
    NSDictionary *params = @{@"name":self.personalNickname,@"intro":self.personalIntro,@"gender":genderStr,@"user_id":self.personalInfo.user_id};
    @weakify(self)
    [BLApi POST:URL_Member_submit parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
        @strongify(self)
        if (!error) {
            BLBaseResponse *response = (BLBaseResponse *)responseObject;
            if ([response isSuccess]) {
                if (self.submitBlock) {
                    self.submitBlock(nil);
                }
                [KSNavi pop];
            } else {
                [self ks_showToast:response.errmsg];
            }
            
        } else {
            DDLogInfo(@"%@",error);
        }
    }];
}

- (void)logout {
    NSLog(@"退出登录");
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定退出登录吗" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击取消");
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击确认");
        
        //确认 清除所有 NSUserDefaults 数据
        NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
        NSDictionary *dictionary = [defatluts dictionaryRepresentation];
        for(NSString *key in [dictionary allKeys]){
            NSLog(@"key===========%@",key);
            [defatluts removeObjectForKey:key];
            [defatluts synchronize];
        }
        [TKAccountManager logout];
        [self ks_showToast:@"退出登录成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:kUDLoginOutSuccess object:nil];
        [self.navigationController popViewControllerAnimated:YES];
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -lazyload
- (IJImagesPicker *)imagesPicker
{
    if (!_imagesPicker) {
        _imagesPicker = [IJImagesPicker new];
    }
    return _imagesPicker;
}
@end
